package com.zrb.mobile;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.Header;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
//import com.amap.api.maps.LocationSource.OnLocationChangedListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.CitylistAdapter;
import com.zrb.mobile.adapter.News_tablistItemAdapter;
import com.zrb.mobile.adapter.model.CityDto;
import com.zrb.mobile.adapter.model.CityDtos;
import com.zrb.mobile.adapter.model.ProjectDtos;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.mobile.adapter.model.UserInfoResult;
import com.zrb.mobile.common.ShareDialog;
import com.zrb.mobile.ui.CenterProgressWebView;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.webkit.WebSettings;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class User_locationActivity extends BaseActivity implements
		AMapLocationListener, OnClickListener, OnItemClickListener {

	// private OnLocationChangedListener mListener;

	private LocationManagerProxy mLocationManagerProxy;

	CitylistAdapter mcitylistAdapter;
	Tip progTip;
	ListView mlistview;
	private int parentAreaCode;

	private int tmpAreaCode;
	private String areaName;
	private TextView mareaload;
	private View netLocContainer;
	private boolean isuCenter = false;
	 

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		setContentView(R.layout.u_center_location);
		if (bundle != null)
			restoreSelf(bundle);
		else {
			parentAreaCode = this.getIntent().getIntExtra("areacode", -1);
			isuCenter = this.getIntent().getBooleanExtra("isucenter", false);
			 
		}

		initView();
		LoadArea();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("areacode", parentAreaCode);
		outState.putBoolean("isucenter", isuCenter);
	}

	private void restoreSelf(Bundle savedInstanceState) {
		parentAreaCode = savedInstanceState.getInt("areacode", -1);
		isuCenter = savedInstanceState.getBoolean("isucenter", false);
	}

	private void initView() {

		// editTextpwd.setText("123456");
		this.findViewById(R.id.title_left_root).setOnClickListener(this);
		;
		TextView txtTitle = (TextView) this.findViewById(R.id.txt_title);
		txtTitle.setText("地  区");
		mareaload = (TextView) this.findViewById(R.id.tv_areaload);

		this.findViewById(R.id.tv_temp_allarea).setOnClickListener(this);

		netLocContainer = this.findViewById(R.id.layout_arealoading);
		netLocContainer.setOnClickListener(this);

		mlistview = (ListView) this.findViewById(R.id.listView1);
		mlistview.setOnItemClickListener(this);

		if (parentAreaCode == -1)
			init();
		else {
			this.findViewById(R.id.tv_location_area).setVisibility(View.GONE);
			netLocContainer.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;

		case R.id.right_title:
			// changeBaseInfo() ;
			break;
		case R.id.layout_arealoading:
			saveGpsArea();
			break;
		case R.id.tv_temp_allarea:
			if (isuCenter)
				return;
			Intent intent = new Intent();
			intent.putExtra("area", "全国");
			intent.putExtra("code", "0");
			User_locationActivity.this.setResult(
					android.app.Activity.RESULT_OK, intent);
			User_locationActivity.this.finish();
			break;
		}
	}

	// 非用户中心的直接返回，否则保存用户城市才返回
	private void saveGpsArea() {

		if (mareaload.getTag() == null)
			return;
		CityDto tmpcity = new CityDto();
		String citycode = mareaload.getTag().toString().substring(0, 4) + "00";
		tmpcity.postcode = Integer.parseInt(citycode);
		;
		tmpcity.cityName = mareaload.getText().toString();
		if (!isuCenter)
			setquickResult(tmpcity);
		else
			saveUserInfoCity(tmpcity, true);
	}

	private void LoadArea() {
		// areaApi/findCityByProvince
		String url = "";
		if (parentAreaCode == -1)
			url = "areaApi/findAllProvince";
		else
			url = "areaApi/findCityByProvince?code=" + parentAreaCode;
		ZrbRestClient.get(url, null, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				// progTip.Dismiss();
				CommonUtil.showToast("加载数据出错！", User_locationActivity.this);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					CityDtos tmpDto = gson.fromJson(results, CityDtos.class);
					if (tmpDto.res == 1) {
						if (mcitylistAdapter == null) {
							mcitylistAdapter = new CitylistAdapter(
									User_locationActivity.this);
							mcitylistAdapter.CurrentDatas.addAll(tmpDto.data);
							mlistview.setAdapter(mcitylistAdapter);
						}
					} else
						CommonUtil.showToast(tmpDto.msg,
								User_locationActivity.this);
				} catch (Exception e) {
					CommonUtil.showToast("加载数据出错！", User_locationActivity.this);
					// System.out.println("eeee!!!!"+e.getMessage());
				}
			}
		});
	}

	/**
	 * 初始化定位
	 */
	private void init() {
		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(this);
		mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mLocationManagerProxy != null) {
			// 移除定位请求
			mLocationManagerProxy.removeUpdates(this);
			// 销毁定位
			mLocationManagerProxy.destroy();
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// TODO Auto-generated method stub
		if (amapLocation != null
				&& amapLocation.getAMapException().getErrorCode() == 0) {
			// 定位成功回调信息，设置相关消息
			/*
			 * mLocationLatlngTextView.setText(amapLocation.getLatitude() + "  "
			 * + amapLocation.getLongitude());
			 * mLocationAccurancyTextView.setText(String.valueOf(amapLocation
			 * .getAccuracy()));
			 * mLocationMethodTextView.setText(amapLocation.getProvider());
			 * 
			 * SimpleDateFormat df = new
			 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new
			 * Date(amapLocation.getTime());
			 * 
			 * mLocationTimeTextView.setText(df.format(date));
			 * mLocationDesTextView.setText(amapLocation.getAddress());
			 */
			/*
			 * if (amapLocation.getProvince() == null) {
			 * mLocationProvinceTextView.setText("null"); } else {
			 * mLocationProvinceTextView.setText(amapLocation.getProvince()); }
			 * mLocationCityTextView.setText(amapLocation.getCity());
			 * mLocationCountyTextView.setText(amapLocation.getDistrict());
			 * mLocationCityCodeTextView.setText(amapLocation.getCityCode());
			 * mLocationAreaCodeTextView.setText(amapLocation.getAdCode());
			 */

			mareaload.setText(amapLocation.getProvince() + " "
					+ amapLocation.getCity());
			mareaload.setTag(amapLocation.getAdCode());
		}

	}

	// 非用户中心直接返回第一级，否则跳转第二级选择
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

		CityDto tmpDto = mcitylistAdapter.CurrentDatas.get(arg2);
		if (!isuCenter) {
			setquickResult(tmpDto);
			return;
		}
		if (parentAreaCode == -1) {
			areaName = tmpDto.cityName;
			tmpAreaCode = tmpDto.postcode;
			Intent intent = new Intent(this, User_locationActivity.class);
			intent.putExtra("areacode", tmpAreaCode);
			intent.putExtra("isucenter", isuCenter);
			this.startActivityForResult(intent, 100);
		} else {
			saveUserInfoCity(tmpDto, false);
		}
	}

	private void setquickResult(final CityDto mlocation) {

		Intent intent = new Intent();
		intent.putExtra("area", mlocation.cityName);
		intent.putExtra("code", mlocation.postcode + "");

		User_locationActivity.this.setResult(android.app.Activity.RESULT_OK,
				intent);
		User_locationActivity.this.finish();

	}

	private void saveUserInfoCity(final CityDto mlocation,
			final boolean isNetloc) {

		if (AppSetting.curUser == null) {
			
			Intent intent = new Intent();
			if (isNetloc) {
				intent.putExtra("area",mlocation.cityName);
				intent.putExtra("code",mlocation.postcode + "");
			} else {
				intent.putExtra("cityname",mlocation.cityName);
				intent.putExtra("citycode",mlocation.postcode);
			}
			User_locationActivity.this.setResult(android.app.Activity.RESULT_OK,intent);
			User_locationActivity.this.finish();
			return;
 		}
			RequestParams param = new RequestParams();
			param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
			param.put("location", mlocation.postcode);
			showloading();
			ZrbRestClient.post("user/updateAppUserInfo", param,
					new AsyncHttpResponseHandler() {
						@Override
						public void onFailure(int arg0, Header[] arg1,
								byte[] arg2, Throwable arg3) {
							// TODO Auto-generated method stub
							progTip.Dismiss();
							CommonUtil.showToast("保存数据出错！",
									User_locationActivity.this);
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1,
								byte[] arg2) {
							// TODO Auto-generated method stub
							String results = new String(arg2);
							progTip.Dismiss();
							try {
								Gson gson = new Gson();
								RegisterDto tmpDtos = gson.fromJson(results,
										RegisterDto.class);
								if (tmpDtos.res == 1) {
									Intent intent = new Intent();
									if (isNetloc) {
										intent.putExtra("area",mlocation.cityName);
										intent.putExtra("code",mlocation.postcode + "");
									} else {
										intent.putExtra("cityname",mlocation.cityName);
										intent.putExtra("citycode",mlocation.postcode);
									}
									User_locationActivity.this.setResult(android.app.Activity.RESULT_OK,intent);
									User_locationActivity.this.finish();
								} else
									CommonUtil.showToast(tmpDtos.msg,User_locationActivity.this);
							} catch (Exception e) {
								CommonUtil.showToast("加载数据出错！",User_locationActivity.this);
								// System.out.println("eeee!!!!"+e.getMessage());
							}
						}
					});
 	}
  
	
	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "正在保存中...", true,
					true);
		else
			progTip.Show("正在保存中...");
	}

	// 回调方法，从第二个页面回来的时候会执行这个方法
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 根据上面发送过去的请求吗来区别
		if (resultCode == android.app.Activity.RESULT_OK) {
			switch (requestCode) {
			case 100:

				String cityname = data.getStringExtra("cityname");
				int cityCode = data.getIntExtra("citycode", -1);

				Intent intent = new Intent();
				intent.putExtra("area", areaName + " " + cityname);
				intent.putExtra("code", tmpAreaCode + "," + cityCode);
				User_locationActivity.this.setResult(
						android.app.Activity.RESULT_OK, intent);
				User_locationActivity.this.finish();
				break;

			default:
				break;
			}
		}
	}

	/*
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub switch (v.getId()) {
	 * 
	 * 
	 * break; case R.id.button_register: Intent it = new Intent(this,
	 * User_registerStep1.class); startActivity(it); break; }
	 * 
	 * }
	 */

}
